package com.example.demo.handler;

import com.example.rabbitmq.starter.handler.FailureHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 邮件通知失败处理器
 * 当消息消费失败达到最大重试次数后，发送邮件通知相关人员
 */
@Component
public class EmailNotificationFailureHandler implements FailureHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(EmailNotificationFailureHandler.class);
    
    @Override
    public void handleFailure(String messageId, String messageContent, String messageType, int retryCount, Exception lastException) {
        try {
            // 构建邮件内容
            String emailSubject = "【系统告警】消息消费失败通知";
            String emailContent = buildEmailContent(messageId, messageContent, messageType, retryCount, lastException);
            
            // 发送邮件通知
            sendEmailNotification(emailSubject, emailContent);
            
            logger.info("消息失败处理完成 - 邮件通知已发送, messageId: {}, messageType: {}, retryCount: {}", 
                       messageId, messageType, retryCount);
            
        } catch (Exception e) {
            logger.error("发送失败通知邮件时出现异常, messageId: {}, error: {}", messageId, e.getMessage(), e);
        }
    }
    
    /**
     * 构建邮件内容
     */
    private String buildEmailContent(String messageId, String messageContent, String messageType, int retryCount, Exception lastException) {
        StringBuilder content = new StringBuilder();
        content.append("<html><body>");
        content.append("<h2 style='color: red;'>消息消费失败通知</h2>");
        content.append("<table border='1' cellpadding='5' cellspacing='0'>");
        content.append("<tr><td><strong>消息ID</strong></td><td>").append(messageId).append("</td></tr>");
        content.append("<tr><td><strong>消息类型</strong></td><td>").append(messageType).append("</td></tr>");
        content.append("<tr><td><strong>重试次数</strong></td><td>").append(retryCount).append("</td></tr>");
        content.append("<tr><td><strong>消息内容</strong></td><td><pre>").append(messageContent).append("</pre></td></tr>");
        content.append("<tr><td><strong>失败原因</strong></td><td style='color: red;'>");
        content.append(lastException != null ? lastException.getMessage() : "未知异常");
        content.append("</td></tr>");
        
        if (lastException != null) {
            content.append("<tr><td><strong>异常堆栈</strong></td><td><pre style='font-size: 12px;'>");
            content.append(getStackTrace(lastException));
            content.append("</pre></td></tr>");
        }
        
        content.append("</table>");
        content.append("<p><em>请及时处理该异常消息。</em></p>");
        content.append("</body></html>");
        
        return content.toString();
    }
    
    /**
     * 获取异常堆栈信息
     */
    private String getStackTrace(Exception e) {
        java.io.StringWriter sw = new java.io.StringWriter();
        java.io.PrintWriter pw = new java.io.PrintWriter(sw);
        e.printStackTrace(pw);
        return sw.toString();
    }
    
    /**
     * 发送邮件通知
     * 这里可以集成具体的邮件服务
     */
    private void sendEmailNotification(String subject, String content) {
        // TODO: 集成具体的邮件服务
        // 例如：Spring Mail、JavaMail等
        
        // 模拟发送邮件
        logger.info("发送邮件通知 - 主题: {}", subject);
        logger.debug("邮件内容: {}", content);
        
        // 实际实现示例：
        // mailService.sendHtmlMail(toEmails, subject, content);
    }
    
    @Override
    public String getHandlerName() {
        return "邮件通知处理器";
    }
}